package com.itany.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年08月08日13:32
 */
public class Test10_事务 {
    public static void main(String[] args) throws DataAccessException {
        User user=new User("bbb","123","11111111","nanjing");
        insertUser(user);
    }
    public static void insertUser(User user) throws DataAccessException {
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            conn=JDBCUtil.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            String sql=new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getPhone());
            ps.setString(4,user.getAddress());

            //执行DML操作
            int rows=ps.executeUpdate();
            int i=1/0;

            //业务全部结束之后，提交事务，此时只要报错，则不会提交
            conn.commit();
        } catch (DataAccessException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
               throw new DataAccessException("事务回滚出错");
            }
            throw e;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
               throw new DataAccessException("事务回滚出错");
            }
            throw new DataAccessException("访问数据库失败");
        }catch (Exception e){
            System.out.println("进入异常了");
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new DataAccessException("事务回滚出错");
            }
            throw e;
        }finally {
            JDBCUtil.close(conn,ps,null);
        }
    }
}
